package st.business.tepth.business.visitor;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.constraint.ConstraintLayout;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import st.business.tepth.R;
import st.business.tepth.R2;
import st.business.tepth.base.OnItemChooseListener;
import st.business.tepth.business.RootDelegate;
import st.business.tepth.business.bean.CommonBean;
import st.business.tepth.business.bean.FactoryInfo;
import st.business.tepth.business.bean.LocationBean;
import st.business.tepth.business.event.ReloadVisitorDataEvent;
import st.business.tepth.business.login.LoginDelegate;
import st.business.tepth.business.setting.SettingDelegate;
import st.business.tepth.manager.UserBean;
import st.business.tepth.manager.UserManager;
import st.shadow.library.core.base.mvp.MvpFragment;
import st.shadow.library.core.storage.ShadowPreference;
import st.shadow.library.core.util.utilcode.util.DeviceUtils;
import st.shadow.library.core.util.utilcode.util.ScreenUtils;
import st.shadow.library.ui.dialog.DialogLoader;
import st.shadow.library.ui.dialog.IDialogClickListener;

/**
 * Author: shadow
 * Email:  1025431817@qq.com
 * Time:   2019-03-05 16:53
 * 游客界面
 */

public class VisitorDelegate extends MvpFragment<VisitorPresenter> implements VisitorContract.View {

    public static VisitorDelegate newInstance() {
        return new VisitorDelegate();
    }

    @BindView(R2.id.tb_station)
    TabLayout mTabStation;
    @BindView(R2.id.view_pager)
    ViewPager mViewPagerStation;
    @BindView(R2.id.layout_container)
    ConstraintLayout mLayoutContainer;
    DialogLoader mDialogLoader;

    @Override
    public VisitorPresenter getPresenter() {
        return new VisitorPresenter(this);
    }

    @Override
    public Object setLayout() {
        return R.layout.delegate_visitor;
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, View rootView) {
        mDialogLoader = new DialogLoader(_mActivity);
        EventBus.getDefault().register(this);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);
        loadData();
    }

    @Subscribe
    public void onReloadEvent(ReloadVisitorDataEvent event) {
        loadData();
    }


    private void loadData() {
        String factoryName = ShadowPreference.getCustomAppProfile("factoryName");
        String androidId = DeviceUtils.getAndroidID();
        if (factoryName.isEmpty()) {
            mPresenter.getFactoryInfo(androidId);
        } else {
            addTopView(R.layout.view_loading, mLayoutContainer);
            mPresenter.getLocationInfo(androidId);
        }
    }

    @OnClick(R2.id.iv_setting)
    public void onSetting() {
        start(SettingDelegate.newInstance());
    }

    @Override
    public void showLocationInfo(LocationBean locationBean) {
        removeTopView(mLayoutContainer);
        if (locationBean != null) {
            List<LocationBean.FactoryAreaListBean> factoryAreaList
                    = locationBean.getFactoryAreaList();
            if (factoryAreaList != null && !factoryAreaList.isEmpty()) {
                mViewPagerStation.setAdapter(new StationAdapter
                        (getChildFragmentManager(), factoryAreaList));
                mTabStation.setupWithViewPager(mViewPagerStation);
                if (factoryAreaList.size() > 6) {
                    mTabStation.setTabMode(TabLayout.MODE_SCROLLABLE);
                } else {
                    mTabStation.setTabMode(TabLayout.MODE_FIXED);
                }
                for (int i = 0, size = factoryAreaList.size(); i < size; i++) {
                    TabLayout.Tab tab = mTabStation.getTabAt(i);
                    if (tab == null) {
                        tab = mTabStation.newTab();
                        mTabStation.addTab(tab);
                    }
                    tab.setCustomView(R.layout.item_tab_station);
                    if (tab.getCustomView() != null) {
                        TextView textView = tab.getCustomView().findViewById(R.id.text);
                        textView.setText(factoryAreaList.get(i).getName());
                    }
                }
                //mViewPagerStation.setOffscreenPageLimit(factoryAreaList.size());
            } else {
                addTopView(R.layout.view_bus_empty, mLayoutContainer);
            }
        }
        //已经绑定维修厂但没有登录认证
        if (!ShadowPreference.getAppFlag("verified")) {
            start(LoginDelegate.newInstance());
        }

    }

    @Override
    public void setInfoSucceed(final String msg) {
        _mActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mDialogLoader.stopProgressWithSuccess(msg, null, new IDialogClickListener() {
                    @Override
                    public void onClick() {
                        mDialogLoader.clearDialog();
                    }
                });
            }
        });
    }

    @Override
    public void showError(final String msg) {
        _mActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                removeTopView(mLayoutContainer);
                addTopView(R.layout.view_bus_empty, mLayoutContainer);
                mDialogLoader.stopProgressWithFailed(msg, msg);
            }
        });

    }

    @Override
    public void verificationFactoryInfo(FactoryInfo factoryInfo) {
        if (factoryInfo != null) {
            final List<FactoryInfo.Factory> allFactory = factoryInfo.getAllFactory();
            if (allFactory != null) {
                _mActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        new DialogBindFactory(_mActivity, allFactory,
                                new DialogBindFactory.OnConfirmListener() {

                                    @Override
                                    public void onChoose(FactoryInfo.Factory factory, CommonBean commonBean) {
                                        mDialogLoader.showProgressDialog(false,
                                                "正在提交", "请稍候...");
                                        mPresenter.setFactoryInfo(DeviceUtils.getAndroidID(),
                                                factory.getId(), commonBean.getId(),
                                                factory.getName() + "-" + commonBean.getName());
                                    }
                                }).show();
                    }
                });
            }
        }
    }

    @Override
    public void succeed(UserBean userBean) {
        if (userBean != null) {
            mDialogLoader.clearDialog();
            if (getParentFragment() != null) {
                UserManager.getInstance().saveUser(userBean);
                ((RootDelegate) getParentFragment()).onLogin();
            }
        }
    }

    @OnClick(R2.id.iv_visitor)
    public void onLogin() {
        DialogLogin dialogLogin = new DialogLogin(_mActivity,
                new OnItemChooseListener<String>() {
                    @Override
                    public void onChoose(String code) {
                        mPresenter.login(code, "123456", 1);
                        mDialogLoader.showProgressDialog(false,
                                "正在登录", "请稍候...");
                    }
                });
        Window dialogWindow = dialogLogin.getWindow();
        if (dialogWindow != null) {
            WindowManager.LayoutParams lp = dialogWindow.getAttributes();
            lp.width = ScreenUtils.getScreenWidth() * 1000 / 1280; // 宽度
            lp.height = ScreenUtils.getScreenHeight() * 820 / 1024; // 高度
            dialogWindow.setGravity(Gravity.CENTER);
            dialogWindow.setAttributes(lp);
            dialogLogin.show();
        }
    }
}